import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import {queryDismissContractList, saveContractInfo,deleteContract,finishContract} from '../../service'
import {Tabs,message,notification,Divider,Popconfirm} from 'antd'
import {endTypeList, contractTempList, employeeStatusList} from "@/utils/constant"
import moment from 'moment'
import DismissForm from '../../components/DismissForm';
import OfflineAddForm from '../OfflineAddForm';
const  { TabPane } = Tabs;

const TableList = ({currentUser}) => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [tabIndex, setTabIndex] = useState("0");
  const [visible, setVisible] = useState(false);
  const [loading,setLoading] = useState(false);
  const [record,setRecord] = useState(null);
  const [completeVisible, setCompleteVisible] = useState(false);
  const { authorities } = currentUser;

  const handleChangTabIndex = (key) => {
    setTabIndex(key);
    if(key === '0'){
      actionRef.current &&  actionRef.current.reload();
    }else{
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const handleCancel = () => {
    setVisible(false);
    setCompleteVisible(false);
    setRecord(null);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveContractInfo(values).then((res) => {
      if(res.flag){
        setVisible(false);
        setRecord(null);
        message.success('操作成功！');
        actionRef.current.reload()
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
      setLoading(false);
    })
  };

  const rescindContract = (record) => {
    setRecord(record);
    setVisible(true);
  };

  const handleCompleteSubmit = (values) => {
    setLoading(true);
    finishContract(values).then((res) => {
      if(res.flag){
        handleCancel();
        message.success('合同发送成功！');
        actionRef.current.reload()
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
      setLoading(false);
    })
  };

  const delContract = (id) =>{
    deleteContract(id).then(res => {
      if (res.flag) {
        message.success('合同删除成功！');
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
    });
  };

  const complete = (record) => {
    setRecord(record);
    setCompleteVisible(true);
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true,
      fixed: 'left',
      width:120
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
      fixed: 'left',
      width:80
    },
    {
      title: '员工状态',
      dataIndex: 'employeestatus',
      hideInSearch: true,
      fixed: 'left',
      width:120,
      render: (text) =>{
        return employeeStatusList.find((item) => item.value === text)?.label;
      }
    },
    {
      title: '公司',
      dataIndex: 'orgName',
    },
    {
      title: '部门',
      dataIndex: 'unitName'
    },
    {
      title: '合同类型',
      dataIndex: 'contractType',
      valueEnum: {
        1: { text: contractTempList[0].label },
        2: { text: contractTempList[2].label },
        3: { text: contractTempList[1].label },
        4: { text: contractTempList[3].label }
      },
    },
    {
      title: '合同期限类型',
      dataIndex: 'contractTimeType',
      render: (text) => {
        return text !== 6 ? '固定期限合同': '无固定期限合同'
      },
    },
    {
      title: '合同状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '未生效', status: 'Default' },
        1: { text: '已生效', status: 'Success' },
        2: { text: '合同过期', status: 'Default' },
      },
    },
    {
      title: '甲方主体',
      dataIndex: 'employerCompany',
      hideInSearch: true,
    },
    {
      title: '合同生效日',
      dataIndex: 'contractBeginDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '合同预计终止日期',
      dataIndex: 'contractEndDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '合同实际终止日期',
      dataIndex: 'endTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '解除合同签订日期',
      dataIndex: 'endSignDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-'  ? moment(text).format('YYYY-MM-DD') : ''
      },
    },
    {
      title: '查看合同',
      dataIndex: 'beginContractUrl',
      hideInSearch: true,
      onCell: ()=>{
        return {
          style:{
            maxWidth:200,
            overflow:'hidden',
            whiteSpace:'nowrap',
            textOverflow:'ellipsis',
            cursor:'pointer',
          }
        }
      },
      render: (text) =>{
        return <a href={text} target="_blank">{text}</a>
      }
    },
    {
      title: '解除合同签订地址',
      dataIndex: 'endContractUrl',
      hideInSearch: true,
      onCell: ()=>{
        return {
          style:{
            maxWidth:200,
            overflow:'hidden',
            whiteSpace:'nowrap',
            textOverflow:'ellipsis',
            cursor:'pointer',
          }
        }
      },
      render: (text) =>{
        return <a href={text} target="_blank">{text}</a>
      }
    },
    {
      title: '解除类型',
      dataIndex: 'endType',
      hideInTable: true,
      valueEnum: {
        1: { text: '合同解除'},
        2: { text: '终止解除'},
        7: { text: '变更'},
      },
    },
    {
      title: '解除类型',
      dataIndex: 'endType',
      hideInSearch: true,
      render: (text) => {
        const res = endTypeList.find((item) => item.value === parseInt(text));
        return res ? res.label : text
      },
    },
  ];

  if(tabIndex === '0'){
    columns.push(
      {
        title: '发送状态',
        dataIndex: 'sendStatus',
        hideInSearch: true,
        render: (text,record) => {
          return (record.esignFlowId) ? "已发送" : "未发送";
        },
      },
      {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          <a onClick={() => rescindContract(record)}>解除合同</a>
          <Divider type="vertical"/>
          {(authorities.indexOf("emp:htlb:delete") > -1) && <>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => delContract(record.id)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical"/>
          </>}
          <a onClick={() => complete(record)}>线下签订</a>
        </>
      ),
    })
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="0" onChange={handleChangTabIndex}>
        <TabPane tab="未签署" key="0">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => queryDismissContractList(params,[0],'2')}
            columns={columns}
            scroll={{ x: '180%' }}
          />
          <DismissForm
            loading={loading}
            record={record}
            visible={visible}
            type={'termination'}
            onCancel={handleCancel}
            onSubmit={handleSubmit}
          />
          <OfflineAddForm
            loading={loading}
            visible={completeVisible}
            record={record}
            onCancel={handleCancel}
            onSubmit={handleCompleteSubmit}
          />
        </TabPane>
        <TabPane tab="已签署" key="1">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => queryDismissContractList(params,[1,2],'2')}
            columns={columns}
            scroll={{ x: '180%' }}
          />
        </TabPane>
      </Tabs>
    </PageHeaderWrapper>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser
}))(TableList)
